package com.stars.empoly.activity

import android.Manifest
import android.graphics.Bitmap
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.map.*
import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.utils.DistanceUtil
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.eazypermissions.common.model.PermissionResult
import com.eazypermissions.coroutinespermission.PermissionManager
import com.qmuiteam.qmui.kotlin.onClick
import com.qmuiteam.qmui.widget.QMUIRadiusImageView
import com.stars.empoly.R
import com.stars.empoly.adapter.ReceivedAdapter
import com.stars.empoly.base.MBActivity
import com.stars.empoly.databinding.ActivityOrderDetailsBinding
import com.stars.empoly.inte.ChoiceData
import com.stars.empoly.model.UseOrderDetail
import com.stars.empoly.utils.DecimalUtils
import com.stars.empoly.utils.PopuCancelUtils
import com.stars.empoly.vmodel.OrderDetailsVModel
import com.trailer.base.utils.DialUtils
import kotlinx.coroutines.launch

/**
 *on 2022/9/23
 * 订单详情--已接单的详情
 */
class OrderDetailsActivity : MBActivity<OrderDetailsVModel, ActivityOrderDetailsBinding>() {

    // 地图View实例
    private var mMapView: MapView? = null
    private var mBaiduMap: BaiduMap? = null
    private var mBitmapDescriptorStart: BitmapDescriptor? = null

    var latEnd: LatLng? = null
    private var mMarker: Marker? = null


    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)

        vm.id = intent?.extras?.getString("id")
        vm.getInfo()
        //设置进度
        vm.bean.observe(this) {


            initMap(it.latitude, it.longitude)
            if (it.technicianStatus == 1) {
                binding.imgOne.visibility = View.VISIBLE
            }
            if (it.technicianStatus == 2) {
                binding.imgOne.visibility = View.VISIBLE
                binding.imgTwo.visibility = View.VISIBLE
            }
            if (it.technicianStatus == 3) {
                binding.imgOne.visibility = View.VISIBLE
                binding.imgTwo.visibility = View.VISIBLE
                binding.imgThree.visibility = View.VISIBLE
            }
            if (it.technicianStatus == 4) {
                binding.imgOne.visibility = View.VISIBLE
                binding.imgTwo.visibility = View.VISIBLE
                binding.imgThree.visibility = View.VISIBLE
                binding.imgFour.visibility = View.VISIBLE
            }

            updateMarker(it)
            var latStart: LatLng? = null
            //算出总距离
            try {

                if (null == it.technicianStatus) {
                    latStart =
                        LatLng(
                            it.technicianStartLatitude.toDouble(),
                            it.technicianStartLongitude.toDouble()
                        )
                } else {
                    latStart =
                        LatLng(it.technicianLatitude.toDouble(), it.technicianLongitude.toDouble())
                }

                latEnd = LatLng(it.latitude.toDouble(), it.longitude.toDouble())

                var s1 = DistanceUtil.getDistance(latStart, latEnd) / 1000

                var z_distance = DecimalUtils.getNumber(s1).toDouble()

                binding.tvDistance.text = "距离你" + z_distance + "km"

                //去开启连续定位
                //获取一次定位todo:
                handler.sendEmptyMessageDelayed(0x101, 1000)
            } catch (e: Exception) {

            }

        }


    }

    private val handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            setLongLocation()
        }
    }


    private fun initMap(latitude: String, longitude: String) {
        mMapView = binding.mapview
        if (null == mMapView) {
            return
        }
        mBaiduMap = mMapView?.map
        if (null == mBaiduMap) {
            return
        }

        // 使得圆角地图情况下，地图log不会被遮盖
        mBaiduMap?.setViewPadding(30, 0, 30, 20)

        // 设置初始中心
        val start = LatLng(latitude.toDouble(), longitude.toDouble())
        val mapStatusUpdate = MapStatusUpdateFactory.newLatLngZoom(start, 12f)
        mBaiduMap?.setMapStatus(mapStatusUpdate)

    }

    /**
     * 更新marker状态
     */
    private fun updateMarker(bean: UseOrderDetail) {

        //设置用户的位置  icon_binding_point  icon_start_custom
        mBitmapDescriptorStart = BitmapDescriptorFactory.fromResource(R.drawable.icon_binding_point)


        val start = LatLng(bean.technicianLatitude.toDouble(), bean.technicianLongitude.toDouble())

        var markerOptions = MarkerOptions()
            .position(start)
            .icon(mBitmapDescriptorStart)
//        mBaiduMap?.addOverlay(markerOptions)

        mMarker = mBaiduMap!!.addOverlay(markerOptions) as Marker


        val inflate: View =
            LayoutInflater.from(this@OrderDetailsActivity).inflate(R.layout.map_view, null)
        var img = inflate.findViewById<QMUIRadiusImageView>(R.id.img)
        if (null != bean.headImage && !TextUtils.isEmpty(bean.headImage)) {

            Glide.with(this@OrderDetailsActivity)
                .asBitmap()
                .load(bean.headImage)
                .into(object : SimpleTarget<Bitmap>() {
                    override fun onResourceReady(
                        resource: Bitmap,
                        transition: Transition<in Bitmap>?
                    ) {
                        img.setImageBitmap(resource)
                        val end = LatLng(bean.latitude.toDouble(), bean.longitude.toDouble())
                        val markerOptions1 = MarkerOptions()
                            .position(end)
                            .icon(BitmapDescriptorFactory.fromView(inflate))
                        mBaiduMap?.addOverlay(markerOptions1)


                    }
                })


        }


    }


    override fun onResume() {
        super.onResume()
        if (null != mMapView) {
            mMapView?.onResume()
        }

    }

    override fun onPause() {
        super.onPause()
        if (null != mMapView) {
            mMapView?.onPause()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            handler.removeMessages(0x101)
//
//            if (null != mMapView) {
//                mMapView!!.onDestroy()
//                mBaiduMap?.clear()
//            }
//
//            if (null != mBitmapDescriptorStart) {
//                mBitmapDescriptorStart?.recycle()
//            }
//            if (null != locationClient) {
//                locationClient?.stop()
//                locationClient = null
//            }
            finish()
            return true
        }
        return false
    }


    override fun onDestroy() {
        super.onDestroy()

        handler.removeMessages(0x101)

        if (null != mMarker) {
            mMarker?.cancelAnimation()
        }
        if (null != mMapView) {
            mMapView!!.onDestroy()
            mBaiduMap?.clear()
        }
        if (null != mBitmapDescriptorStart) {
            mBitmapDescriptorStart?.recycle()
        }
        if (null != locationClient) {
            locationClient?.stop()
            locationClient = null
        }

    }


    override fun listeners() {
        super.listeners()
        binding.butCancel.onClick {
            PopuCancelUtils.show(context(), binding.butCancel, object : ChoiceData {
                override fun onRestuse(id: String?) {
                    //todo 同意取消订单
                }

            })
        }

        binding.llPhone.onClick {

            //拨打电话
            launch {
                val requestPermissions = PermissionManager.requestPermissions(
                    this@OrderDetailsActivity, 1000, Manifest.permission.CALL_PHONE
                )
                if (requestPermissions is PermissionResult.PermissionGranted) {
                    //拨打电话
                    vm.bean.value?.phone?.let {
                        DialUtils.dialPhone(context(), it)
                    }
                }
            }
        }


    }

    override fun vmClass(): Class<OrderDetailsVModel> {
        return OrderDetailsVModel::class.java
    }

    override fun binding(): ActivityOrderDetailsBinding {
        return ActivityOrderDetailsBinding.inflate(layoutInflater)
    }

    override fun title(): String? {
        return "订单详情"
    }

    //一次定位
    private var locationClient: LocationClient? = null


    fun setLongLocation() {
        locationClient = LocationClient(context())
        // 设置定位条件
        val option = LocationClientOption()

        option.setIsNeedLocationPoiList(true) //获取附近 poi

//        option.setIsNeedLocationDescribe(true); //位置语义化
        option.isOpenGps = true // 是否打开GPS

        option.setCoorType("bd09ll") // 设置返回值的坐标类型

//        option.setScanSpan(5000) // 设置定时定位的时间间隔。单位毫秒
//        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setAddrType("all")
        option.setIgnoreKillProcess(false) //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.setOnceLocation(true)

        locationClient?.locOption = option

        locationClient?.registerLocationListener(object : BDAbstractLocationListener() {
            override fun onReceiveLocation(amapLocation: BDLocation?) {
                if (null != amapLocation) {


                    try {
                        var latStart =
                            LatLng(amapLocation.latitude, amapLocation.longitude)

                        var s1 = DistanceUtil.getDistance(latStart, latEnd) / 1000

                        var distance = DecimalUtils.getNumber(s1).toDouble()

                        binding.tvDistance.text = "距离你" + distance + "km"

                        //移动market

                        mMarker?.position = latStart
//

                    } catch (e: Exception) {

                    }


                }

                handler.sendEmptyMessageDelayed(0x101, 3000)

            }
        })
        locationClient?.locOption = option

        locationClient?.start()

    }


}
